<template>
  <div class="loginbox">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="账户">
        <el-input v-model="form.loginname"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input show-password v-model="form.pwd"></el-input>
      </el-form-item>
      <el-form-item label=" ">
        <el-button @click="login()" type="primary">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";

export default {
  data() {
    return {
      form: {
        loginname: "",
        pwd: "",
      },
    };
  },
  methods: {
    //映射Vuex 中的添加Tabs函数
    ...mapMutations(["changeJWT"]),
    login() {
      //登录
      //let that = this;
      axios({
        method: "post",
        url: "/Login",
        data: {
          Loginname: this.form.loginname,
          Loginpwd: this.form.pwd,
        },
      })
        .then((response) => {
          console.log(response);
          if (response.data.code == 1) {
            this.$message.success("登录成功！");
            //Token 过期时间
            let expires = new Date(response.data.expires);
            let token = response.data.token;
            sessionStorage.setItem("token", token);
            sessionStorage.setItem("expires", expires);

            sessionStorage.setItem("headImg", axios.defaults.baseURL+response.data.user.img.path);
            sessionStorage.setItem("username", response.data.user.name);
            this.$router.push(
              this.$route.query.redirect ? this.$route.query.redirect : "/"
            );
          } else {
            this.$message.error(response.data.msg);
          }
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("数据异常，请稍后再试");
        });
    },
  },
};
</script>

<style>
.loginbox {
  width: 333px;
  margin: 120px auto;
}
</style>